package com.j2110.controller.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //获取登录信息
        String name = (String) req.getSession().getAttribute("LOGIN_NAME");
        //如果用户没用登录
        if (name == null){
            //登录则放行
            if (req.getRequestURL().toString().contains("/img")||req.getRequestURL().toString().contains("/css")||req.getServletPath().equals("/login.jsp")||req.getServletPath().equals("/user")||req.getServletPath().equals("/randomCode")){
                chain.doFilter(request, response);
            }else {
                //未登录则
                //重定向到登录界面
                resp.sendRedirect(req.getContextPath() + "/login.jsp");

            }
        }else {
            //登录则无法重复登录
            if (!req.getServletPath().equals("/login.jsp")) {
                chain.doFilter(request, response);
            }else {
                resp.sendRedirect(req.getContextPath() + "/emp/index");
            }
        }
    }
}
